package maple.core;

import java.util.HashMap;
import java.util.logging.Level;
import java.util.Vector;

import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAException;

import maple.lang.Language;

public abstract class Consumer extends MapleAgent
{
	protected String _operator;
	protected Vector< String > _preconditions;
	protected String _postcondition;
	
	public Consumer( final Language.Instruction instruction, final int number )
	{
		_min_arguments = number + 1;
		
		_operator = instruction.toString();
		_preconditions = new Vector< String >();
		_postcondition = "";
	}

	/**
	 * de-register services
	 *
	 * @author	snowfoxy
	 * @since	2011-12-18
	 */
	protected void deregister()
	{
		try
		{
			DFService.deregister( this );
		}
		catch( FIPAException e )
		{
			_logger.log( Level.WARNING, "", e );
		}
	}

	/**
	 * register services
	 *
	 * @author	snowfoxy
	 * @since	2011-11-26
	 */
	protected void register()
	{
		Vector< String > names = new Vector< String >();
		names.add( _operator );
		Vector< String > types = new Vector< String >();
		types.add( _postcondition );
		Vector< String > ops = new Vector< String >();
		ops.add( toOperator() );
		Vector< String > pres = new Vector< String >();
		pres.add( toPrecondition() );
		Vector< String > posts = new Vector< String >();
		posts.add( _postcondition );
		
		try
		{
			DFService.register( this, getInstance( names, types, ops, pres, posts ) );
		}
		catch( FIPAException e )
		{
			_logger.log( Level.WARNING, "", e );
			doDelete();
		}
	}

	/**
	 * return the String representation of the precondition
	 *
	 * @return	the String representation of the precondition
	 *
	 * @author	snowfoxy
	 * @since	2011-11-26
	 */
	protected String toPrecondition()
	{
		String condition = "";
		
		for( String precondition : _preconditions )
		{
			condition = condition
				       + Language.COMMA
					   + precondition;
		}

		if( condition.length() > 0 )
		{
			condition = condition.substring( 1 );
		}

		return condition;
	}

	protected abstract String toOperator();
}
